package org.clob4eclipse.handlers;

import java.io.IOException;
import java.io.InputStream;


import org.clob4eclipse.Activator;
import org.clob4eclipse.Config;
import org.clob4eclipse.PluginData;
import org.clob4eclipse.PluginLogger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class OracleSaveHandler extends AbstractHandler {
	/**
	 * The constructor.
	 */
	public OracleSaveHandler() {
	}
	
	/**
	 * the command has been executed, so extract extract the needed information
	 * from the application context.
	 */
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
		
		Shell shell = window.getShell();
		Config config = null;
		InputStream stream = null;
		
		IEditorPart editor = Activator.getActiveEditor();
		if (editor != null) {
			IFile activeFile = Activator.getIFileFromEditor(editor);
			
			if (activeFile != null) {
				PluginData data = Activator.getPluginData();
				try {
					config = new Config(data);
					stream = activeFile.getContents();
					
					String fileName = activeFile.getName().substring(0, activeFile.getName().length()-5);
					
					PluginLogger.logInfo("file name="+activeFile.getName());
					PluginLogger.logInfo("file name sub="+activeFile.getName().substring(0, activeFile.getName().length()-5));

					config.commitClobFile(stream, fileName, shell);
					
				} catch (Exception e) {
					PluginLogger.logError("error saving clob", e);
					MessageDialog.openInformation(
							shell,
							"OracleClobEditor Plug-in",
							"FAILED: Save '"+activeFile.getName()+"'!");
				} finally {
					try {
						if (stream != null)	stream.close();
					} catch (IOException e1) {
					}				
				}		
			}		
		}		
		return null;
	}
}
